//
//  CallDoctorViewController.m
//  Telemedicine
//
//  Created by Trong Ton on 5/14/14.
//  Copyright (c) 2014 Trong Ton. All rights reserved.
//

#import "CallDoctorViewController.h"
#import "JMImageCache.h"

@interface CallDoctorViewController ()

@end

@implementation CallDoctorViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    firstCheck = YES;
    NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    int startYView = ([[vComp objectAtIndex:0] intValue] >= 7)?20:0;
    
    UIView *bigImageConten = [[UIView alloc] initWithFrame:CGRectMake(0, startYView, self.view.bounds.size.width, 237)];
    [self.view addSubview:bigImageConten];
    [bigImageConten release];
    
    UIImageView *bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 217)];
    
    NSString *linkImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"BackgroundImageLink"];
    if (linkImage && linkImage.length > 0) {
        [bigImageView setImageWithURL:[NSURL URLWithString:linkImage] placeholder:[UIImage imageNamed:@"background_call_default.jpg"]];
    }
    else {
        bigImageView.image = [UIImage imageNamed:@"background_call_default.jpg"];
    }
    [bigImageConten addSubview:bigImageView];
    [bigImageView release];
    
    imageCallButton = [UIButton buttonWithType:UIButtonTypeCustom];
    imageCallButton.frame = bigImageView.bounds;
    [imageCallButton addTarget:self action:@selector(provideButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [bigImageConten addSubview:imageCallButton];
    
    int startY = 217;
    BOOL checkTerm = [[NSUserDefaults standardUserDefaults] boolForKey:@"TermsWasCheck"];
    if(checkTerm == NO) {
        termsButton = [UIButton buttonWithType:UIButtonTypeCustom];
        termsButton.frame = CGRectMake(0, startY, self.view.bounds.size.width, 20);
        [termsButton setBackgroundImage:[UIImage imageNamed:@"terms_unchecked.png"] forState:UIControlStateNormal];
        [termsButton setBackgroundImage:[UIImage imageNamed:@"terms_checked.png"] forState:UIControlStateDisabled];
        [termsButton addTarget:self action:@selector(termsButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        [bigImageConten addSubview:termsButton];
        startY += 20;
    }
    
    callListContent = [[UIScrollView alloc] initWithFrame:CGRectMake(0, startY + startYView, self.view.bounds.size.width, self.view.bounds.size.height - startY - startYView - 49)];
    [self.view addSubview:callListContent];
    [callListContent release];
    
    startY = 0;
    providerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    providerButton.frame = CGRectMake(0, startY, self.view.bounds.size.width, 48);
    [providerButton setBackgroundImage:[UIImage imageNamed:@"choose_people_call_provider.png"] forState:UIControlStateNormal];
    NSString *linkFirstImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"FirstButtonImageLink"];
    if (linkFirstImage && linkFirstImage.length > 0) {
        [[JMImageCache sharedCache] imageForURL:[NSURL URLWithString:linkFirstImage] completionBlock:^(UIImage *image) {
            [providerButton setBackgroundImage:image forState:UIControlStateNormal];
        }];
    }
    
    [providerButton addTarget:self action:@selector(provideButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [callListContent addSubview:providerButton];
    
    startY += 49;
    UIButton *schedulingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    schedulingButton.frame = CGRectMake(0, startY, self.view.bounds.size.width, 48);
    [schedulingButton setBackgroundImage:[UIImage imageNamed:@"choose_people_call_schedule.png"] forState:UIControlStateNormal];
    NSString *linkSecondImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"SecondButtonImageLink"];
    if (linkSecondImage && linkSecondImage.length > 0) {
        [[JMImageCache sharedCache] imageForURL:[NSURL URLWithString:linkSecondImage] completionBlock:^(UIImage *image) {
            [schedulingButton setBackgroundImage:image forState:UIControlStateNormal];
        }];
    }
    [schedulingButton addTarget:self action:@selector(schedulingButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [callListContent addSubview:schedulingButton];
    
    startY += 49;
    UIButton *assistanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    assistanButton.frame = CGRectMake(0, startY, self.view.bounds.size.width, 48);
    [assistanButton setBackgroundImage:[UIImage imageNamed:@"choose_people_call_medical_assistant.png"] forState:UIControlStateNormal];
    NSString *linkThreeImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"ThreeButtonImageLink"];
    if (linkThreeImage && linkThreeImage.length > 0) {
        [[JMImageCache sharedCache] imageForURL:[NSURL URLWithString:linkThreeImage] completionBlock:^(UIImage *image) {
            [assistanButton setBackgroundImage:image forState:UIControlStateNormal];
        }];
    }
    [assistanButton addTarget:self action:@selector(assistanButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [callListContent addSubview:assistanButton];
    
    startY += 49;
    UIButton *billingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    billingButton.frame = CGRectMake(0, startY, self.view.bounds.size.width, 48);
    [billingButton setBackgroundImage:[UIImage imageNamed:@"choose_people_call_billing.png"] forState:UIControlStateNormal];
    NSString *linkFourImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"FourBroundImageLink"];
    if (linkFourImage && linkFourImage.length > 0) {
        [[JMImageCache sharedCache] imageForURL:[NSURL URLWithString:linkFourImage] completionBlock:^(UIImage *image) {
            [billingButton setBackgroundImage:image forState:UIControlStateNormal];
        }];
    }
    [billingButton addTarget:self action:@selector(billingButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [callListContent addSubview:billingButton];
    
    startY += 49;
    if(startY < callListContent.bounds.size.height - 23) {
        startY = callListContent.bounds.size.height - 23;
    }
    phoneInfo = [[UIImageView alloc] initWithFrame:CGRectMake(0, startY, self.view.bounds.size.width, 23)];
    [phoneInfo setImage:[UIImage imageNamed:@"home_bottomwebsite_url.jpg"]];
    [callListContent addSubview:phoneInfo];
    [phoneInfo release];
    
    NSLog(@"conten callListContent.y = %d", (startY + 23));
    [callListContent setContentSize:CGSizeMake(callListContent.bounds.size.width, (startY + 23))];//(startY + 25))];//startY+bottomView.bounds.size.height)];
    callListContent.scrollEnabled = YES;
    
    _loadingView = [[MBProgressHUD alloc] initWithView:self.view];
    _loadingView.animationType = MBProgressHUDAnimationZoom;
    _loadingView.labelText = @"Loading...";
    [self.view addSubview:_loadingView];
    [_loadingView release];
    [_loadingView hide:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    BOOL showPopup = [[NSUserDefaults standardUserDefaults] boolForKey:@"showOpendSkype"];
    if(showPopup == YES) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"showOpendSkype"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"Please first make sure you have logged in Skype." delegate:self cancelButtonTitle:@"Open Skype" otherButtonTitles:nil, nil];
        alert.tag = 50001;
        [alert show];
        [alert release];
    }
    //was check in function get doctor, it don't need call
//    [self checkEnableCallDoctor];
}

- (void)dealloc {
    if(docArray) {
        [docArray release];
    }
    [super dealloc];
}

- (void)checkEnableCallDoctor {
    NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
    if (codeString && codeString.length > 0) {
        [self checkEnableCall:codeString];
    }
}

- (void)showTermsView {
    backgroundContent = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    backgroundContent.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
    [self.view addSubview:backgroundContent];
    [backgroundContent release];
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, backgroundContent.bounds.size.width - 40, backgroundContent.bounds.size.height - 40)];
    contentView.backgroundColor = [UIColor whiteColor];
    [backgroundContent addSubview:contentView];
    [contentView release];
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height - 40)];
//    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"telemedicine_term_and_condition" ofType:@"html"];
    NSString* htmlString = @"<html><head>    <title>MD24 Telemedicine’s Term and Condition </title></head><body><h2>    <b>    MD24 Telemedicine’s Term and Condition    </b>    </h2><p>    THESE USER’S AND LICENSEE’S TERMS OF SERVICE (THE \"AGREEMENT\") ARE A LEGAL AGREEMENT BETWEEN MD24 HOUSE CALL INC (DBA \"MD24 HOUSE CALL\" OR “MD24”) AND YOU (\"USER\" OR \“LICENSEE\”). YOU SHOULD REVIEW THIS ENTIRE AGREEMENT BEFORE YOU DECIDE WHETHER TO ACCEPT THIS AGREEMENT AND CONTINUE WITH THE REGISTRATION PROCESS.BY CLICKING \"I AGREE TO THE TERMS AND CONDITION\" BELOW AND CLICKING ON THE \"COMPLETE SIGN UP\" BUTTON YOU AGREE TO BE BOUND BY THIS AGREEMENT.    </p><p> <b> 1.	Definitions </b> </p><p>1.1	\"Authorized Users\" means Licensee's employees and contractors with access to MD24 Simply Connect Software.<br>1.2	\"Effective Date\" means the date on which MD24 executed this Agreement as set forth on the signature page.<br>1.3	\"Software\" means MD24’s version of Simply Connect software for Android Samsung tablets and other available smart phones.<br>1.4	“MD24 Simply Connect Widget” means partner software used to enhance the values of of MD24 Simply Connect Software. <br>1.5	“Licensee(s)” means the partner(s) working with MD24House Call as either distributer such as home health agencies, hospice, etc. <br>1.6	“User(s)” means the direct consumer utilizing the software and access the service providers, i.e. direct patients paying the monthly fee for software to access telemedicine clinician.</p><p> <b> 2.	License </b> </p>Subject to the terms and conditions of this Agreement, MD24 grants to Licensee and User a nontransferable, nonexclusive limited right to confidential Simply Connect software access(es) at a small monthly fee. The MD24 will also provide Simply Connect software, installation and upgrades.  <br>(a)	Licensee/User may not modify or alter the Simply Connect Software, MD24 Simply Connect Widget(s) or the MD24’s End User Agreement that accompanies the Simply Connect Software as provided by MD24 to Licensee. As a condition of the rights granted herein, each installation of the MD24 Simply Connect software will result in a MD24’s icon residing on the Smart Phone of each authorized user with future lock-down option.<br>(b)	Any use of the Simply Connect Software licensed pursuant to this Agreement by the Licensee/User and/or its Authorized Users is subject to terms and conditions of the MD24 End User License.<br>(c)	Licensee/User agrees not to modify, reverse engineer, reverse compile, or otherwise disassemble the Simply Connect Software. Licensee/User may not use, reproduce, sublicense, display, distribute or dispose of the Software, in whole or in part, other than as expressly permitted under this Agreement. Licensee/User agrees that it will not display or distribute any screen shots of the MD24 Simply Connect Software without MD24’s prior written consent.<br>(d)	At its option, MD24 may authorize Licensee/User by notice to distribute to authorized users a newer version of the Simply Connect Software pursuant to the terms of this Agreement. In the event that MD24 makes a newer version available pursuant to the terms of this Agreement, upon written request from MD24, Licensee/User agrees that Licensee/User will stop distributing the older version within 5 business days after receiving MD24’s request. MD24 House Call will have no obligation to license new versions to Licensee/User under this Agreement, or to license new versions to Licensee/User at all.<br>(e)	Licensee/User acknowledges that the Simply Connect Software is proprietary to MD24 and that MD24 retains all right, title, and interest in the Simply Connect Software, including without limitation all copyrights, patents, trademarks and other proprietary rights. Except as expressly set forth herein, no other rights or licenses are granted or to be implied.<br>(f)	Licensee/User acknowledges that all video teleconference files will automatically be stored in the MD24 House Call’s server per then current HIPPA requirements. The visit records and the video files are available upon request with patient’s consent by law.<p> <b> 3.	Termination </b> </p>3.1 This Agreement will continue until terminated pursuant to this section 3. Either party may terminate this Agreement at any time by providing 30-day written notice to the other party. This Agreement will automatically terminate in the event that Licensee/User becomes insolvent, has a receiver appointed, makes an assignment for the benefit of creditors, or becomes the subject of any proceeding under any bankruptcy, insolvency, or debtor’s relief law. <br>3.2	In the event of any termination of this Agreement, all Licensee/User’s rights granted herein shall immediately cease except as provided in this paragraph. Licensee/User will have 5 business days to remove the Simply Connect Software from its Smart Phone. Termination of this Agreement will also terminate all End User Licenses accepted by Licensee/User and/or Licensee's Authorized Users. No delay, omission or failure to exercise any right or remedy provided for in this Agreement shall be deemed a waiver thereof, nor shall it be deemed to be a waiver of any other or subsequent breach. The rights of the parties under this clause are in addition to any other rights and remedies provided by law or under this Agreement. Sections 1, 2(a), 2(c), 2(d), 2(e), 3.2, 5, 6, 7, 8, 9, 10, 11, 12 and 13 shall survive termination of this Agreement.<br><p> <b> 4.	Disclaimer of Warranties and Limitation of Liabilities. </b> </p>4.1	The Simply Connect Access Software is licensed to Licensee/User on an \"AS IS\" basis. MD24 MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE SOFTWARE LICENSED HEREUNDER, INCLUDING WITHOUT LIMITATION, WARRANTIES WITH RESPECT TO MERCHANT ABILITY, NONINFRINGEMENT OR FITNESS FOR ANY PARTICULAR PURPOSE.<br>4.2	IN NO EVENT SHALL MD24 BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES RELATING TO THIS AGREEMENT, THE SOFTWARE, WHETHER UNDER A THEORY OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE) OR OTHERWISE, EVEN IF MD24 HAS BEEN MADE AWARE OF THE POSSIBILITY OF SUCH DAMAGES. LICENSEE ACKNOWLEDGES THAT THIS ALLOCATION OF RISKS IS A PART OF THE BARGAIN OF THIS AGREEMENT. MD24’s total liability under this Agreement, however arising, shall not exceed five dollars.<br><p> <b> 5.	Indemnification </b> </p>5.1	MD24 has no obligation to indemnify, defend or hold Licensee/User harmless from and against any claim that the Telemedicine Access Software licensed hereunder infringes any third party patent, copyright, trademark or other intellectual property right. Licensee/User will promptly notify MD24 of any such claim.5.2	To the extent permitted by applicable law, Licensee/User will indemnify, defend and hold MD24 harmless from any and all claims, damages, losses, liabilities, costs and expenses (including reasonable fees of attorneys and other professionals) arising out of or in connection with Licensee/User's and its distributors' distribution of the Telemedicine Access Software, unless the claim arises solely out of the Simply Connect Access Software as originally provided by MD24 to Licensee. The foregoing exception will not apply to a claim arising out of the combination of the Simply Connect Access Software with any other software or hardware. MD24 will promptly notify Licensee of any such claim and will provide reasonable cooperation and assistance in connection with such claims.<p> <b> 6.	SERVICE FEES AND PAYMENT TERMS </b> </p>6.1	Service Fees: PAYMENT GUARANTEE POLICY. FOR TRANSACTIONS CONDUCTED THROUGH A VISIT WITH A SERVICE PROVIDER CONNECTED THROUGH THE SOFTWARE, THE LICENSEE/USER WILL BE CHARGED SEPARATELY THORUGH EITHER USER’S INSURANCE OR SELF PAY FOR THE SPECIFIC SERVICE(S).  THE MD24 WILL NOT BE RESPONSIBLE FOR THE AMOUNT CHARGED BY THE SERVICE PROVIDER(S), WHICH ARE SEPARATE ENTITIES FROM MD24. MD24 RESERVES THE RIGHT TO EARN INTEREST AND/OR OTHER COMPENSATION FROM ITS SERVICE PROVIDER BANKS OR OTHERS ARISING FROM THE PROCESSING OF PAYMENT TRANSACTIONS THAT HAVE NOT SETTLED TO USER.6.2	REFUNDS AND ADJUSTMENTS. MD24 WILL DISCLOSE ITS RETURN/CANCELLATION POLICY ON THE MD24 WEBSITE(S). IF THERE ARE RETURNS, CANCELLATIONS OR PRICE ADJUSTMENTS IN CONNECTION WITH A PAYMENT TRANSACTION, MD24 WILL INITIATE A CREDIT TO THE USER USING THE REFUND FUNCTION OF THE SERVICE WITHIN FIVE (5) WORKING DAYS OF RECEIVING THE BUYER'S REQUEST. REFUNDS CANNOT EXCEED THE TOTAL AMOUNT OF THE PAYMENT TRANSACTION. MD24 WILL NOT TO ACCEPT CASH OR ANY OTHER CONSIDERATION FROM A USER IN EXCHANGE FOR ISSUING A REFUND TO A USER. MD24 WILL NOT TO GIVE CASH REFUNDS TO A USER IN CONNECTION WITH A PRODUCT PAID FOR WITH THE SERVICE UNLESS REQUIRED BY LAW. IF THE REFUNDS AND ADJUSTMENT IS REQUIRED FROM THE PARTNERED SERVICES (I.E. TELEMEDICINE SERVICES ITSELF), MD24 IS NOT RESPONSIBLE FOR THE SERVICE CHARGE(S).  MD24 IS ONLY RESPONSIBLE FOR THE SOFTWARE MONTHLY CHARGE CONNECTING USERS TO THE NETWORK SERVICE PROVIDERS (I.E. TELEMEDICINE, LEGAL, IT SERVICES, ETC.).6.3	TAXES AND OTHER CHARGES. USERS WILL PAY ANY APPLICABLE TAXES, INCLUDING SALES, USE, PERSONAL PROPERTY, VALUE-ADDED, EXCISE, CUSTOMS FEES, IMPORT DUTIES OR STAMP DUTIES OR OTHER TAXES AND DUTIES IMPOSED BY GOVERNMENTAL ENTITIES OF WHATEVER KIND AND IMPOSED WITH RESPECT TO THE TRANSACTIONS UNDER THIS AGREEMENT, INCLUDING PENALTIES AND INTEREST, BUT SPECIFICALLY EXCLUDING TAXES BASED UPON MD24’S NET INCOME.<p> <b> 7.	Notices </b> </p>Any notice required under this Agreement will be deemed given: (i) when delivered personally, (ii) by facsimile, (iii) five (5) days after having been sent by registered or certified mail, return receipt requested, postage prepaid, (iv) via electronic mail, or (v) as otherwise expressly provided in this Agreement.MD24 WILL ADDITIONALLY COMMUNICATE WITH USERS REGARDING THE SERVICE BY MEANS OF ELECTRONIC COMMUNICATIONS, INCLUDING:(I) SENDING ELECTRONIC MAIL TO THE EMAIL ADDRESS SELLER PROVIDED TO MD24 DURING REGISTRATION OR(II) POSTING OF NOTICES OR COMMUNICATIONS ON WEBSITE(S) BELONGED TO MD24. MD24 AND USER AGREE THAT MD24 MAY COMMUNICATE BY MEANS OF ELECTRONIC COMMUNICATIONS THE FOLLOWING TYPES AND CATEGORIES OF COMMUNICATIONS AND RECORDS: THIS AGREEMENT (AND REVISIONS OR AMENDMENTS), NOTICES OR DISCLOSURES REGARDING THE SERVICE, PAYMENT AUTHORIZATIONS, AND ANY OTHER MATTER RELATING TO SELLER'S USE OF THE SERVICE. USER IS RESPONSIBLE FOR PROVIDING ITS OWN HARDWARE, SOFTWARE AND ELECTRONIC ACCESS TO THE INTERNET IN ORDER TO USE THE SERVICE AND ACCESS THE ELECTRONIC COMMUNICATIONS. USER SHOULD MAINTAIN COPIES OF ELECTRONIC COMMUNICATIONS BY PRINTING A PAPER COPY OR SAVING AN ELECTRONIC COPY ON USER’S COMPUTER. ELECTRONIC COMMUNICATIONS WILL BE DEEMED RECEIVED BY USER WHEN MD24 SENDS THE ELECTRONIC COMMUNICATION TO THE EMAIL ADDRESS OF USER PROVIDED AT THE TIME OF REGISTRATION OR AS REVISED BY USER THEREAFTER IN ACCORDANCE WITH THIS AGREEMENT OR WHEN MD24 POSTS THE ELECTRONIC COMMUNICATION ON A MD24 WEBSITE. FOR THOSE CATEGORIES OF COMMUNICATIONS OR RECORDS THAT MD24 IS OTHERWISE REQUIRED UNDER APPLICABLE LAW TO PROVIDE IN A WRITTEN PAPER FORM TO USER, MD24 AND USER AGREE THAT MD24 MAY PROVIDE THE COMMUNICATIONS OR RECORDS TO SELLER BY MEANS OF ELECTRONIC COMMUNICATIONS.<p> <b> 8.	Export </b> </p>Licensee/User may not use or otherwise export or re-export the MD24 Simply Connect Software except as authorized by United States law and the laws of the jurisdiction in which the MD24 Simply Software was obtained. In particular, but without limitation, the MD24 Simply Connect Software may not be exported or re-exported (a) into any U.S. embargoed countries or (b) to anyone on the U.S. Treasury Department's list of Specially Designated Nationals or the U.S. Department of Commerce Denied Person’s List or Entity List. By using the MD24 Simply Connect Software, Licensee/User represents and warrants that Licensee/User is not located in any such country or on any such list. Licensee/User also agrees that Licensee/User will not use the MD24 Simply Connect Software for any illegal purposes prohibited by United States law, including, without limitation, the illegal development, design, manufacture or production.<p> <b> 9.	Assignment </b> </p>This Agreement is binding on the assigns, heirs and successors (whether through merger or otherwise) of the parties, except that it may not be assigned by Licensee/User by any means, including without limitation, by operation of law or merger. Any attempted assignment of this Agreement in violation of this section voids the Agreement.<p> <b> 10.	Relationship of the Parties </b> </p>Neither party may represent or bind the other party in any way and nothing stated in this Agreement will be construed as creating the relationship of joint ventures, partners, employer and employee, franchisor and franchisee, master and servant, or principal and agent.<p> <b> 11.	Publicity </b> </p>Licensee/User agrees that it will not make any press releases or public announcements referring to this Agreement without MD24’s prior consent.<p> <b> 12.	Governing Law </b> </p>This Agreement will be governed by and construed in accordance with the laws of the State of Arizona as applied to agreements entered into and to be performed entirely within Arizona between Arizona residents. Any litigation or other dispute resolution between the parties relating to this Agreement will take place in the Maricopa County, Arizona. The parties consent to the personal jurisdiction of, and venue in, the state and federal courts within Maricopa County.<p> <b> 13.	Complete Understanding </b> </p>This Agreement constitutes the entire Agreement between the parties concerning the use and distribution of the MD24 Simply Connect Access Software licensed hereunder. Any waiver or amendment of any provision of this Agreement will be effective only if in writing and signed by authorized representatives of both parties.</body></html>";
    
//    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"telemedicine_term_and_condition" ofType:@"html"]isDirectory:NO]]];
    
    [webView loadHTMLString:htmlString baseURL:nil];
    [contentView addSubview:webView];
    [webView release];
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    closeButton.frame = CGRectMake(2, contentView.bounds.size.height - 38, contentView.bounds.size.width - 4, 36);
    closeButton.backgroundColor = [UIColor lightGrayColor];
    [closeButton setTitle:@"OK" forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(closeButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:closeButton];
}

- (void)showListDoctor {
    UIView * contentAddVideo = [[UIView alloc] initWithFrame:self.view.bounds];
    contentAddVideo.tag = 300003;
    [self.view addSubview:contentAddVideo];
    [contentAddVideo release];
    
    UIButton *closeContent = [UIButton buttonWithType:UIButtonTypeCustom];
    closeContent.frame = contentAddVideo.bounds;
    closeContent.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
    [closeContent addTarget:self action:@selector(closeContenAddView:) forControlEvents:UIControlEventTouchUpInside];
    [contentAddVideo addSubview:closeContent];
    
    UITableView *doctorTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 20, contentAddVideo.bounds.size.width - 40, contentAddVideo.bounds.size.height - 40)];
    doctorTableView.dataSource = self;
    doctorTableView.delegate = self;
    [contentAddVideo addSubview:doctorTableView];
    [doctorTableView release];
    [doctorTableView reloadData];
}

- (void)closeContenAddView:(UIButton *)sender {
    UIView *content = [self.view viewWithTag:300003];
    [content removeFromSuperview];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    int count = docArray!=nil?[docArray count]:0;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"UIDoctorTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                reuseIdentifier:cellIdentifier] autorelease];
    }
    // Leave cells empty if there's no data yet
    NSString *doctorName = [[docArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    NSString *skypeName = [[docArray objectAtIndex:indexPath.row] objectForKey:@"skype"];
    if(doctorName) {
        cell.textLabel.text = doctorName;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Skype: %@",skypeName];
        cell.detailTextLabel.textColor = [UIColor colorWithRed:51.0/255.0 green:181.0/255.0 blue:229.0/255.0 alpha:1.0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    return  cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isDoctorCall = NO;
    if(isDoctorCall) {
        NSString *skype = [[NSUserDefaults standardUserDefaults] objectForKey:@"your_skype"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Are you sure you want to receive calls from our doctors? If yes, your Skype will be launched and needs to login with %@, then wait for a call in few minutes.", skype] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        alertView.tag = indexPath.row;
        [alertView show];
        [alertView release];
    }
    else {
        NSString *doctorWillCall = [[docArray objectAtIndex:indexPath.row] objectForKey:@"skype"];
        NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
        [self sendInfoCall:doctorWillCall withCodeUser:codeString];
        [self closeContenAddView:nil];
        [[AppDelegate sharedDelegate]callSkypeWithName:doctorWillCall];
    }
}

#pragma mark - handle button

- (void)closeButtonPress:(id)sender {
    [backgroundContent removeFromSuperview];
    [termsButton removeFromSuperview];
    callListContent.frame = CGRectMake(0, callListContent.frame.origin.y - 20, callListContent.frame.size.width, callListContent.frame.size.height + 20);
    if(phoneInfo.frame.origin.y < callListContent.bounds.size.height - 23) {
        phoneInfo.frame = CGRectMake(callListContent.frame.origin.x, callListContent.bounds.size.height - 23, phoneInfo.bounds.size.width, phoneInfo.bounds.size.height) ;
    }
}

- (void)termsButtonPress:(id)sender {
    UIButton *button = (UIButton *) sender;
    button.enabled = NO;
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"TermsWasCheck"];
    [self showTermsView];
}

- (void)provideButtonPress:(id)sender {
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input"
//                                                    message:@"Please input Apple ID"
//                                                   delegate:self
//                                          cancelButtonTitle:@"Done"
//                                          otherButtonTitles:nil];
//    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
//    [alert show];
//    [alert release];
//    return;
    
    retrySendCount = 0;
    BOOL isCheck = [[NSUserDefaults standardUserDefaults] boolForKey:@"TermsWasCheck"];
    if (isCheck == YES) {
        [_loadingView show:YES];
        retrySendGetListSkype = 0;
        NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
        [self getDoctorAvailable:codeString];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"You have to check on checkbox" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)schedulingButtonPress:(id)sender {
    BOOL isCheck = [[NSUserDefaults standardUserDefaults] boolForKey:@"TermsWasCheck"];
    if (isCheck == YES) {
        if (kTestVersion == NO) {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"schedulermd24"];
        }
        else {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"htphuong82"];
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"You have to check on checkbox" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)assistanButtonPress:(id)sender {
    BOOL isCheck = [[NSUserDefaults standardUserDefaults] boolForKey:@"TermsWasCheck"];
    if (isCheck == YES) {
        if(kTestVersion == NO) {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"medicalassistantmd24"];
        }
        else {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"htphuong82"];
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"You have to check on checkbox" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)billingButtonPress:(id)sender {
    BOOL isCheck = [[NSUserDefaults standardUserDefaults] boolForKey:@"TermsWasCheck"];
    if (isCheck == YES) {
        if(kTestVersion == NO) {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"paymentmd24"];
        }
        else {
            [[AppDelegate sharedDelegate]callSkypeWithName:@"htphuong82"];
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"You have to check on checkbox" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)callDoctorWithArray:(NSArray *)array {
    if (array && [array count] >= 1) {
        NSString *doctorWillCall = @"";
        if(doctorWillCall == nil || doctorWillCall.length == 0) {
            doctorWillCall  = [[array objectAtIndex:0] objectForKey:@"skype"];
        }
        [[NSUserDefaults standardUserDefaults] setObject:doctorWillCall forKey:@"DoctorInHistory"];
        
        NSString *skype = [[NSUserDefaults standardUserDefaults] objectForKey:@"your_skype"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Are you sure you want to receive calls from our doctors? If yes, your Skype will be launched and needs to login with %@, then wait for a call in few minutes.", skype] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
//        [[AppDelegate sharedDelegate]callSkypeWithName:doctorWillCall];
//        [[AppDelegate sharedDelegate]callFaceTimeWithEmail:doctorWillCall];
//        BOOL isCallSkype = [[NSUserDefaults standardUserDefaults] boolForKey:@"isCallSkype"];
//        if(isCallSkype == NO) {
//            NSString *emailGoogle = [[array objectAtIndex:0] objectForKey:@"email_address"];
//            if([emailGoogle isKindOfClass:[NSNull class]] || emailGoogle == nil || emailGoogle.length == 0) {
//                emailGoogle = @"htphuong82@yahoo.com";
//            }
//            [[AppDelegate sharedDelegate]callFaceTimeWithEmail:emailGoogle];
//        }
//        else {
//            [[AppDelegate sharedDelegate]callSkypeWithName:doctorWillCall];
//        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"All doctor is busy. Please call again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

#pragma mark - handle API

- (void)checkEnableCall:(NSString *)codeString {
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        APIsBaseService *serVice = [APIsBaseService service];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:codeString forKey:@"code"];
        
        [serVice requestWithURL:kCheckCodeValidate
                         params:param
                   successBlock:^(NSDictionary *dictionary){
                       NSLog(@"dic = %@", [dictionary description]);
                       NSString *codeString = [dictionary objectForKey:@"code"];
                       NSString *skypeUser = [dictionary objectForKey:@"skype_name"];
                       [[NSUserDefaults standardUserDefaults] setObject:skypeUser forKey:@"your_skype"];
                       [[NSUserDefaults standardUserDefaults] synchronize];
                       if(codeString && codeString.length > 0) {
                           BOOL status = [[dictionary objectForKey:@"status"] boolValue];
                           isCallValidate = status;
                       }
                       else {
                           isCallValidate = NO;
//                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"An unknow error has occurred, there might be problems with the data format from our server. Please try again in few seconds." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
//                           [alert show];
//                           [alert release];
                       }
                   }
                     errorBlock:^(NSError *error){
                         isCallValidate = NO;
//                         NSLog(@"[error localizedRecoverySuggestion] = %@", [error localizedRecoverySuggestion]);
//                         NSDictionary *userInfo = [error userInfo];
//                         NSString *errorString = [userInfo objectForKey:@"NSLocalizedDescription"];
//                         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
//                         [alert show];
//                         [alert release];
                     }
                     httpMethod:@"GET"];
    }
    else {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alertView show];
//        [alertView release];
    }
}

- (void)sendInfoCall:(NSString *)docterSkype withCodeUser:(NSString *)codeString {
    //http://tele.mobile-solution.org/code_controller/start_call/code=123&doctor_skype=hctdk
    
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        APIsBaseService *serVice = [APIsBaseService service];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:codeString forKey:@"code"];
        [param setObject:docterSkype forKey:@"doctor_skype"];
        [param setObject:[NSNumber numberWithBool:YES] forKey:@"call_from_doctor"];
        
        [serVice requestWithURL:kSendInfoCall
                         params:param
                   successBlock:^(NSDictionary *dictionary){
                       NSLog(@"dic = %@", [dictionary description]);
//                       NSString *skype = [[NSUserDefaults standardUserDefaults] objectForKey:@"your_skype"];
//                       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Press okay and a doctor will call %@ in few seconds, please make sure you log in Skype.", skype] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
//                       [alertView show];
//                       [alertView release];
                   }
                     errorBlock:^(NSError *error){
                         if(retrySendCount < 3) {
                             retrySendCount++;
                             [self sendInfoCall:docterSkype withCodeUser:codeString];
                         }
                     }
                     httpMethod:@"POST"];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)getDoctorAvailable:(NSString *)code {
    //http://tele.mobile-solution.org/doctor_controller/getall
    //http://tele.mobile-solution.org/doctor_controller/getall_by_code/DGjxjm
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        NSString *linkAddCode = [kGetDoctorAvailable stringByAppendingString:[NSString stringWithFormat:@"/%@",code]];
        APIsBaseService *serVice = [APIsBaseService service];
        [serVice requestWithURL:linkAddCode
                         params:nil
                   successBlock:^(NSDictionary *dictionary){
                       id objetGet = [dictionary objectForKey:@"docs"];
                       if ([objetGet isKindOfClass:[NSArray class]]) {
                           if(docArray) {
                               [docArray release];
                               docArray = nil;
                           }
                           docArray = [[NSArray alloc] initWithArray:objetGet];
                           if(docArray && [docArray count] > 0) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   [self showListDoctor];
                               });
                           }
                           else {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"All doctors are busy at the moment. Please make a call later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                               [alert show];
                               [alert release];
                           }
                           
//                           [self callDoctorWithArray:docArray];
                       }
                       else {
                           NSString *message = @"";
                           if([[dictionary objectForKey:@"error"] isEqualToString:@"UserDisable"]) {
                               message = @"This account has been disable, please check your mail box for more details.";
                           }
                           else if ([[dictionary objectForKey:@"error"] isEqualToString:@"UserNotExist"]) {
                               message = @"This account does not exist, please register one or contact admin to enable it.";
                           }
                           else {
                               message = @"An unknown error has occurred, there might be problems with our server. Please try again in few seconds.";
                           }
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                           [alert show];
                           [alert release];
                       }
                       [_loadingView hide:YES];
                   }
                     errorBlock:^(NSError *error){
                         if(retrySendGetListSkype < 3) {
                             retrySendGetListSkype++;
                             [self getDoctorAvailable:code];
                         }
                         else {
                             [_loadingView hide:YES];
                             NSDictionary *userInfo = [error userInfo];
                             NSString *errorString = [userInfo objectForKey:@"NSLocalizedDescription"];
                             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                             [alert show];
                             [alert release];
                         }
                     }
                     httpMethod:@"GET"];
    }
    else {
        [_loadingView hide:YES];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 50001) {
        [[AppDelegate sharedDelegate]callSkypeWithName:@""];
        return;
    }
    if(buttonIndex == 1) {
        int index = alertView.tag;
        NSString *doctorWillCall = [[docArray objectAtIndex:index] objectForKey:@"skype"];
        NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
        [self sendInfoCall:doctorWillCall withCodeUser:codeString];
        [self closeContenAddView:nil];
        [[AppDelegate sharedDelegate]callSkypeWithName:@""];
    }
//    NSString *emailCall = [alertView textFieldAtIndex:0].text;
//    NSLog(@"%@", emailCall);
//    if([self validateEmail:emailCall]) {
//        [[AppDelegate sharedDelegate]callFaceTimeWithEmail:emailCall];
//    }
//    else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"Account don't validate" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];
//    }
}

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:candidate];
}

@end
